﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class CellItem : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public Color color;
    private bool[,] body;
    private Transform startPos;
    private const int size = 5;
    private Image[] images;
    private Vector3 resetPos;

    void OnEnable()
    {
        Show();
    }

    void Start()
    {
        Init();
    }

    void Show()
    {
        images = GetComponentsInChildren<Image>();
    }

    void Init()
    {
        body = new bool[size, size];
        for (int i = 0; i < images.Length; i++)
        {
            string[] index = images[i].name.Split(new char[] {'_'});
            int x = int.Parse(index[0]);
            int y = int.Parse(index[1]);
            body[x, y] = true;
            images[i].color = color;
        }
        startPos = images[0].transform;
    }

    private Vector3 offset;
    public void OnBeginDrag(PointerEventData eventData)
    {
        offset = Input.mousePosition - transform.position;
        resetPos = transform.position;
    }

    public void OnDrag(PointerEventData eventData)
    {
        transform.position = Input.mousePosition - offset;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        GameManager.GetInstance().Check(startPos.position, body, color);
    }

    private void Hide()
    {
        gameObject.SetActive(false);
    }

    private void Reset()
    {
        
    }
}
